/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.kcrx.autoweightapp.fragment.viewmodes
import androidx.lifecycle.*
import cn.kcrx.autoweightapp.data.NewCashBoxRecord
import cn.kcrx.autoweightapp.data.NewCashBoxRepository
import cn.kcrx.autoweightapp.models.NewCashBoxSetting
import cn.kcrx.autoweightapp.utils.XToastUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import java.lang.Exception
import java.util.*
import javax.inject.Inject

@HiltViewModel
class FramentMainAutoViewModel@Inject internal constructor(
    private val newCashBoxRepository: NewCashBoxRepository
):ViewModel() {
    private val logger=KotlinLogging.logger {  }
    private val _mainWeight=MutableLiveData(NewCashBoxSetting.settinglist[0].weight)
    val mainWeight:LiveData<Float>
    get() = _mainWeight
    private val _mainWeightRange=MutableLiveData(NewCashBoxSetting.settinglist[0].weightrange)
    val mainWeightRange:LiveData<Float>
    get()=_mainWeightRange

    private val _mainTestWeight=MutableLiveData(0.0f)
    val mainTestWeight:LiveData<Float>
    get() = _mainTestWeight

    private val _mainTestResult=MutableLiveData("异常")
    val mainTestResult:LiveData<String>
    get() = _mainTestResult

 //   val newCashBoxRecords=newCashBoxRepository.getAll().asLiveData()
    private val _todayRecords=MutableLiveData<MutableList<NewCashBoxRecord>>(mutableListOf())
    val todayRecords:LiveData<MutableList<NewCashBoxRecord>>
    get()=_todayRecords

    fun setMainWeight(weight:Float){
        _mainWeight.value=weight
    }
    fun setMainWeightRange(weightrange:Float){
        _mainWeightRange.value=weightrange
    }
    fun insertDBRecord(cashname:String){
        val newCashBoxRecord=NewCashBoxRecord(cashname,_mainTestWeight.value!!)
        _todayRecords.value!!.add(newCashBoxRecord)

        viewModelScope.launch {
            try {
                val rs=  withContext(Dispatchers.IO){
                    newCashBoxRepository.insert(newCashBoxRecord)
                }
                XToastUtils.success("称重结果记录成功")
            }catch (e:Exception){
                XToastUtils.error("称重结果记录失败!!!")
            }
         }
    }

    fun setMainTestWeight(weight: Float){
        if( _mainTestWeight.value!=weight)
        {
            logger.error { "发现测试重量变化=$weight" }
            if(weight>=0.0f){
                _mainTestWeight.value=weight
                val maxweight=mainWeight.value!!+mainWeightRange.value!!
                val minweight=mainWeight.value!!-mainWeightRange.value!!
                //检查测试重量是否在标定范围
                if(weight>0.0f){
                    if(weight in minweight..maxweight){
                        setMainTestResult("正常")
                        logger.error { "正常 测试重量=$weight 最小重量=$minweight 最大重量=$maxweight" }
                    }else{
                        setMainTestResult("异常")
                        logger.error { "异常 测试重量=$weight 最小重量=$minweight 最大重量=$maxweight" }

                    }
                }
            }
        }
    }

    fun setMainTestResult(res:String){
        logger.error { "发现测试结果=$res" }
        _mainTestResult.value=res
    }

}